/** 微信小程序尺寸比 */
export const miniSizeScale = {
    3: 1000000,
    4: 500000,
    5: 200000,
    6: 100000,
    7: 50000,
    8: 50000,
    9: 20000,
    10: 10000,
    11: 5000,
    12: 2000,
    13: 1000,
    14: 500,
    15: 200,
    16: 100,
    17: 50,
    18: 50,
    19: 20,
    20: 10
}


/** 原生方法获取定位 */
const getLocation = (): Promise<UniApp.GetLocationSuccess | null> => {
    return new Promise((resolve) => {
        uni.getLocation({
            type: 'gcj02',
            success(locRes) { resolve(locRes) },
            fail() { resolve(null) }
        })
    })
}

/** 获取当前定位信息 */
export const getCurrentPosition = (): Promise<UniApp.GetLocationSuccess | null> => {
    return new Promise((resolve, reject) => {
        uni.getSetting({
            success(res) {
                const locationStatus: boolean | undefined = res.authSetting['scope.userLocation'];
                if (locationStatus === undefined) { // 用户还未授权地理位置
                    uni.authorize({
                        scope: 'scope.userLocation',
                        success() { // 授权成功
                            getLocation().then(locRes => {
                                locRes ? resolve(locRes) : reject(locRes)
                            })
                        },
                        fail() { // 拒绝授权
                            reject(null)
                        }
                    })
                } else if (locationStatus) { // 用户同意地理位置授权
                    getLocation().then(locRes => {
                        locRes ? resolve(locRes) : reject(locRes)
                    })
                } else { // 用户拒绝地理位置授权
                    uni.openSetting({
                        success(setRes) {
                            if (setRes.authSetting['scope.userLocation']) {
                                getLocation().then(locRes => {
                                    locRes ? resolve(locRes) : reject(locRes)
                                })
                            } else reject(null)
                        },
                        fail() { reject(null) }
                    })
                }
            },
            fail() { reject(null) }
        })
    })
}

/**
 * 地图尺寸转换
 * @param len 手机像素 单位px
 * @param scale 当前地图比例 scale
 * @returns 实际长度 单位m
 */
export const translateMapLens = (len: number, scale: number) => {
    // 1cm -> 28px
    return Math.floor(len / 28) * Reflect.get(miniSizeScale, Math.floor(scale));
}